package com.company.emallbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.emallbackend.entity.Comment;
import com.company.emallbackend.entity.Order;
import com.company.emallbackend.entity.ProductOrder;
import com.company.emallbackend.entity.User;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.mapper.CommentMapper;
import com.company.emallbackend.mapper.OrderMapper;
import com.company.emallbackend.mapper.ProductOrderMapper;
import com.company.emallbackend.service.ICommentService;
import com.company.emallbackend.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanlijian
 * @since 2023-01-13
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductOrderMapper productOrderMapper;
    
    @Override
    public void commentProduct(Comment comment) {
        if(Objects.isNull(comment)){
            throw new CommonException(201,"请检查您的评论内容");
        }
        Integer productId = comment.getProductId();
        if(Objects.isNull(productId)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        //TODO 下单之后,待评价的状态才能评价商品
        User user = TokenUtils.getCurrentAdmin();
        Integer userId = user.getId();
        if(Objects.isNull(userId)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        //根据用户id查询订单表
        List<Order> orderList = orderMapper.selectList(new QueryWrapper<Order>().eq("user_id", userId));
        if(!CollectionUtils.isEmpty(orderList)){
            List<Integer> orderIds = orderList.stream().map(order -> order.getId()).collect(Collectors.toList());
            //根据订单id查询商品列表
            Set<Integer> productIds=new HashSet<>();
            for (Integer orderId : orderIds) {
                //根据订单查询商品id集合
                List<ProductOrder> productOrderList = productOrderMapper.selectList(new QueryWrapper<ProductOrder>().eq("order_id", orderId));
                for (ProductOrder productOrder : productOrderList) {
                    productIds.add(productOrder.getProductId());
                }
            }
            if(!productIds.contains(productId)){
                throw new CommonException(201,"该商品您并未购买过,不能评论");
            }
            comment.setUserId(userId);
            //评论商品
            commentMapper.insert(comment);
        }
    }
}
